<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\Redis;

/**
 * 匹配-say hi日志
 */
class MeetSayHiLogs extends Base
{
    /**
     * 格式：MEET:SAY:HI:LOG:{user_id}:{to_user_id}
     *
     * @var string
     */
    private $cacheKeyPrefix = 'MEET:SAY:HI:LOG:';//缓存中redis的key

    /**
     * 表名字
     * @var string
     */
    protected $table = 'meet_say_hi_logs';

    /**
     * 指示模型是否自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     * 模型日期列的存储格式。
     *
     * @var string
     */
    protected $dateFormat = 'U';

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['id', 'user_id', 'to_user_id', 'created_at'];

    /**
     * 构造函数
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 获取缓存key
     *
     * @param int $userId
     * @param int $toUserId
     * @return string
     */
    private function getCacheKey(int $userId, int $toUserId): string
    {
        return $this->cacheKeyPrefix . $userId . ':' . $toUserId;
    }

    /**
     * 获取日志
     *
     * @param int $userId
     * @param int $toUserId
     * @return bool
     */
    public function getSayHiLog(int $userId, int $toUserId): bool
    {
        $cacheKey = $this->getCacheKey($userId, $toUserId);
        $cache = Redis::GET($cacheKey);
        if ($cache == null) {
            $this->setCache($userId, $toUserId);
            $cache = Redis::GET($cacheKey);
        }

        return $cache ? false : true;
    }

    /**
     * 重置缓存
     *
     * @param int $userId
     * @param int $toUserId
     * @return bool
     */
    public function setCache(int $userId, int $toUserId): bool
    {
        $cacheKey = $this->getCacheKey($userId, $toUserId);
        Redis::DEL($cacheKey);
        $record = self::query()->where('user_id', $userId)->where('to_user_id', $toUserId)->count();
        Redis::SET($cacheKey, $record ? 1 : 0);
	//过期时间一个月
	Redis::EXPIRE($cacheKey, 30 * 24 * 3600);
        return true;
    }
}
